package cn.vcjf.washcar.common.util;

import cn.vcjf.washcar.common.util.httpUtils.HttpClientUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class QiniuUploadFile {

	public static String ACCESS_KEY = "szMuTwZ1WmGxpuKeND7yjHVpEv-DWQvQtq8we_61";
	public static String SECRET_KEY = "I9XgEnyq2m9OtQ_19WLGIrqyOrmCPxess4XzqcT-";

	public static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
	// 重用 uploadManager。一般地，只需要创建一个 uploadManager 对象
	public static UploadManager uploadManager = new UploadManager();

	// 简单上传，使用默认策略
	public static String getUpToken(String key) {
		if (key != null && !key.equals("")) {
			removeFile(key);
			return auth.uploadToken("washcar", key);//指定上传文件保存的空间名,覆盖上传
		} else {
			return auth.uploadToken("washcar");//指定上传文件保存的空间名
		}
	}


	//删除单个文件
	public static void removeFile(String fileName) {
		//实例化一个BucketManager对象
		BucketManager bucketManager = new BucketManager(auth);
		//要测试的空间和key，并且这个key在你空间中存在
		String bucket = "washcar";
		try {
			//调用delete方法移动文件
			bucketManager.delete(bucket, fileName);
		} catch (QiniuException e) {
			//捕获异常信息
			Response r = e.response;
			System.out.println(r.toString());
		}
	}

	/**
	 * 上传文件（图片）到七牛
	 *
	 * @param file     文件（图片）
	 * @param fileName 新的文件名
	 */
	public static void upload(File file, String fileName) {
		try {
			/**
			 * 上传数据
			 *
			 * @param data     上传的数据 byte[]、File、filePath
			 * @param key      上传数据保存的文件名
			 * @param token    上传凭证
			 * @param params   自定义参数，如 params.put("x:foo", "foo")
			 * @param mime     指定文件mimetype
			 * @param checkCrc 是否验证crc32
			 * @return
			 * @throws QiniuException
			 */
			Response res = uploadManager.put(file, fileName, getUpToken(fileName));
			System.out.println(res.toString());
			System.out.println(res.bodyString());
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时简单状态信息
			System.out.println(r.toString() + "..........");
			try {
				// 响应的文本信息
				System.out.println(r.bodyString() + "---------");
			} catch (QiniuException e1) {
				//ignore
			}
		}
	}


	public static void main(String[] args) {
		String filePath = "http://wx.qlogo.cn/mmopen/RtbBIO0qibnNRCal18Pn7FtIRkmBb4k4OxGdM9epn88UZoDxc3cr0r8PamibDKW56aaXlkmgQFhzqKGk5grJWjNYIcIPaCmk8b/0";
		byte[] bs = getInputStream(filePath);
		String fileName = "0620123456789.jpg";
//		upload(bs, fileName);
	}

	/**
	 * 获取路径上的图片并保存到七牛服务器
	 *
	 * @param filePath 服务器的图片路径
	 * @param fileName 新的文件名
	 */
	public static void upload(String filePath, String fileName) {
		try {
			/**
			 * 上传数据
			 *
			 * @param data     上传的数据 byte[]、File、filePath
			 * @param key      上传数据保存的文件名
			 * @param token    上传凭证
			 * @param params   自定义参数，如 params.put("x:foo", "foo")
			 * @param mime     指定文件mimetype
			 * @param checkCrc 是否验证crc32
			 * @return
			 * @throws QiniuException
			 */
			byte[] bs = getInputStream(filePath);//获取服务器上的文件并转成byte[]
			if (bs != null && bs.length > 0) {
				Response res = uploadManager.put(bs, fileName, getUpToken(fileName));//把byte数据（图片）上传到七牛服务器
				System.out.println(res.toString());
				System.out.println(res.bodyString());
			}
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时简单状态信息
			System.out.println(r.toString() + "..........");
			try {
				// 响应的文本信息
				System.out.println(r.bodyString() + "---------");
			} catch (QiniuException e1) {
				//ignore
			}
		}
	}

	/**
	 * 将二进制流保存到七牛服务器
	 *
	 * @param bs       服务器的图片路径
	 * @param fileName 新的文件名
	 */
	public static void upload(byte[] bs, String fileName) {
		try {
			/**
			 * 上传数据
			 *
			 * @param data     上传的数据 byte[]、File、filePath
			 * @param key      上传数据保存的文件名
			 * @param token    上传凭证
			 * @param params   自定义参数，如 params.put("x:foo", "foo")
			 * @param mime     指定文件mimetype
			 * @param checkCrc 是否验证crc32
			 * @return
			 * @throws QiniuException
			 */
			if (bs != null && bs.length > 0) {
				Response res = uploadManager.put(bs, fileName, getUpToken(fileName));//把byte数据（图片）上传到七牛服务器
				System.out.println(res.toString());
				System.out.println(res.bodyString());
			}
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时简单状态信息
			System.out.println(r.toString() + "..........");
			try {
				// 响应的文本信息
				System.out.println(r.bodyString() + "---------");
			} catch (QiniuException e1) {
				//ignore
			}
		}
	}

	// 从服务器获得一个输入流(本例是指从服务器获得一个image输入流)
	public static byte[] getInputStream(String URL_PATH) {
		InputStream inputStream = null;
		HttpURLConnection httpURLConnection = null;

		try {
			if (!URL_PATH.contains("http://")) {
				URL_PATH = "http://" + URL_PATH;
			}
			URL url = new URL(URL_PATH);
			httpURLConnection = (HttpURLConnection) url.openConnection();
			if (url.getFile() == null || url.getFile().equals("")) {
				return null;
			}
			// 设置网络连接超时时间
			httpURLConnection.setConnectTimeout(3000);
			// 设置应用程序要从网络连接读取数据
			httpURLConnection.setDoInput(true);

			httpURLConnection.setRequestMethod("GET");
			int responseCode = httpURLConnection.getResponseCode();
			if (responseCode == 200) {
				// 从服务器返回一个输入流
				inputStream = httpURLConnection.getInputStream();
			} else {
				return null;
			}
			ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
			byte[] buff = new byte[100];
			int rc = 0;
			while ((rc = inputStream.read(buff, 0, 100)) > 0) {
				swapStream.write(buff, 0, rc);
			}
			byte[] in2b = swapStream.toByteArray();
			return in2b;

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	public static String imgTo64(String filePath) throws IOException {
//		String filePath = "D:\\Documents\\Pictures\\1.png";//图片路径
		FileInputStream fis = null;
		File file = new File(filePath);
		int l = (int) (file.length());
		byte[] src = new byte[l];
		fis = new FileInputStream(file);
		fis.read(src);
		String file64 = Base64.encodeToString(src, 0);
		return file64;
	}
	public static String put64(String file64) {
		try{
			String url = "http://up-z2.qiniup.com/putb64/" + -1;
			System.out.println(url);
			HttpPost post = new HttpPost(url);
			post.addHeader("Content-Type", "application/octet-stream");
			post.addHeader("Authorization", "UpToken " + getUpToken("washcar"));
			System.out.println( "UpToken " + getUpToken("washcar"));
			//		post.setEntity(new ByteArrayEntity(src));
			post.setEntity(new StringEntity(file64));
			System.out.println(file64);

			HttpClient c = HttpClientUtils.getConnection();
			HttpResponse res = c.execute(post);
			System.out.println(res.getStatusLine());
			String responseBody = EntityUtils.toString(
					res.getEntity(), "UTF-8");
			System.out.println(responseBody);
			JSONObject object = JSON.parseObject(responseBody);

			return object.getString("key");
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
}
